package com.lge.clock.alarmclock;

import java.util.Calendar;
import java.util.Date;
import java.util.Vector;

import java.util.Locale;

import com.lge.clock.alarmclock.StopSnoozeButton.SnoozeListener;
import com.lge.clock.alarmclock.StopSnoozeButton.StopListener;
import com.lge.clock.util.CommonUtil;
import com.lge.clock.util.Log;
import com.lge.clock.util.CommonUtil.OPERATOR;

import com.lge.clock.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnKeyListener;
import android.database.Cursor;
import android.graphics.drawable.AnimationDrawable;

import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.format.DateFormat;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class AlarmDialog extends Activity  implements SnoozeListener, StopListener, AlarmConstants {
	
	private String TAG = "AlarmDialog";
	
	private int mId;
    private int mSnooze;
    private long mTime;
    private String mMemo;
    private String mstrPuzzle;
    private String mTone;
    private String mVib;
    private String mGubun;
    private String stopFlag;
    private String mTitle;
    
    private String sideButtons;
    private static final String PREFERENCES = "com.lge.clock_preferences";
    
    private CharSequence apm;
    private String mHour01;
    private String mHour02;
    private String mMinute01;
    private String mMinute02;
    
    private ContentResolver mResolver;
    
    private final String[] mNumDigitDrawables = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
    
    private boolean is24Hours = false;
    
    private boolean mPlaying = true;
    
    private Intent i;
    
    private String temp_TONE    = "";
    private String temp_VIB     = ""; 
    private String temp_MEMO    = ""; 
    private String temp_PUZZLE  = "";
    
    private boolean mPouch;
    
    private AlertDialog alarmDialog;
    
    static int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
    
    private static final Vector mSavings = new Vector(100);

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		/*[START] 2012.05.16 suein1209.kim VZW auto snooze alarm issue, when bluetooth calling*/
//		AlarmAlertWakeLock.acquireCpuWakeLock(this);
		/*[END] 2012.05.16 suein1209.kim VZW auto snooze alarm issue, when bluetooth calling*/
		
		mResolver =	getContentResolver();
		requestWindowFeature(android.view.Window.FEATURE_NO_TITLE);
		final Window win = getWindow();
		win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED|WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
	
		Intent closeDialogs = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
		sendBroadcast(closeDialogs);
		
		SharedPreferences prefs = this.getSharedPreferences(PREFERENCES, 0);
        sideButtons  = prefs.getString("volume_button_setting", "1");
		
		this.setContentView(R.layout.timerdialog);
		i   =	getIntent();
        mId   	   =	i.getIntExtra("id", 0);     
        mSnooze    =	i.getIntExtra("snooze", 0);    
        mMemo	   =	i.getStringExtra("memo");  
        mstrPuzzle =	i.getStringExtra("puzzle");
        mTone	   =	i.getStringExtra("tone");  	
        mVib	   =	i.getStringExtra("vib");   
        mTime	   =	i.getLongExtra("time", 0l);  
        stopFlag   =	i.getStringExtra("stop");
        mGubun	   =	i.getStringExtra("gubun");
        
        mCalendar = Calendar.getInstance();
        
        if(mMemo == null){
        	Log.i(TAG, "mMemo is null");
        	mTitle = "Alarm";
        }else{
        	if(mMemo.length() > 0){
        		mTitle = mMemo;
        	}else{
        		mTitle = "Alarm";
        	}
        	
        }
        
        multiCheck(mId, mTime, false);    
        
        Log.i(TAG, "mGubun => " + mGubun);
        
        updateLayout();
	}
	
	
	/**
	 * suein1209.kim
	 * Show pouch dialog mode
	 */
	private void showPouchDialog(){
		Log.d(TAG, "AlarmDialog -> showPouchDialog() : show pouch dialog, when calling");
		
		View mView = LayoutInflater.from(this).inflate(R.layout.alarm_alert_pouch, null);
		setContentView(mView);
		
		StopSnoozeButton mStopSnoozeButton = (StopSnoozeButton) findViewById(R.id.bb);
		mStopSnoozeButton.setStopListener(this);
		mStopSnoozeButton.setSnoozeListener(this);
		
		/*update init*/
		time_init();
		
		/*play the animation*/
		playClockAnimation();
	} //End of Method showPouchDialog
	
	/**
	 * 2012.05.09
	 * suein1209.kim
	 * snooze changed
	 */
	public void snoozeChanged() {
		Log.d(TAG, "AlarmDialog -> showPouchDialog() -> snoozeChanged() : click the snooze");
		dialogSnoozeChanged();
		mPlaying = false;
		finish();
	}

	/**
	 * 2012.05.09
	 * suein1209.kim
	 * stop changed
	 */
	public void stopChanged() {
		Log.d(TAG, "AlarmDialog -> showPouchDialog() -> snoozeChanged() : click the stop");
		dialogStopChanged();
		mPlaying = false;
		finish();
	}
	
	/**
	 * suein1209.kim
	 * play the clock animation
	 */
	private void playClockAnimation(){
		ImageView mAlarmIcon = (ImageView) findViewById(R.id.alarmIcon);
		mAlarmIcon.setImageResource(R.drawable.alarm_alert_pouch_animation);
		AnimationDrawable mAnimation = (AnimationDrawable) mAlarmIcon.getDrawable();
		mAnimation.stop();
		mAnimation.start();
	} //End Of Method playClockAnimation
	
	private Calendar mCalendar;
	private TextView dateString;// , AMText, PMText;
	
	/**
	 * time output on the screen
	 */
	// alarm screen update every 1 min.
	public void time_init() {
		dateString = (TextView) findViewById(R.id.dateString);
		mCalendar = Calendar.getInstance();
		updateTime();
	}
	
	/**
	 * suein1209.kim
	 * update time
	 */
	private void updateTime() {

		TextView apm;
		TextView mHour01;
		TextView mHour02;
		TextView mMinute01;
		TextView mMinute02;

		mCalendar.setTimeInMillis(System.currentTimeMillis());
		int minutes = mCalendar.get(Calendar.MINUTE);
		int hour = mCalendar.get(Calendar.HOUR);

		String[] strMONTH = {
				getResources().getString(R.string.sp_january_SHORT),
				getResources().getString(R.string.sp_February_SHORT),
				getResources().getString(R.string.sp_march_SHORT),
				getResources().getString(R.string.sp_april_SHORT),
				getResources().getString(R.string.sp_may_SHORT),
				getResources().getString(R.string.sp_june_SHORT),
				getResources().getString(R.string.sp_july_SHORT),
				getResources().getString(R.string.sp_august_SHORT),
				getResources().getString(R.string.sp_september_SHORT),
				getResources().getString(R.string.sp_october_SHORT),
				getResources().getString(R.string.sp_november_SHORT),
				getResources().getString(R.string.sp_december_SHORT) };

		String[] yoil = { "",
				getResources().getString(R.string.sp_sunday_NORMAL),
				getResources().getString(R.string.sp_monday_NORMAL),
				getResources().getString(R.string.sp_tuesday_NORMAL),
				getResources().getString(R.string.sp_wednesday_NORMAL),
				getResources().getString(R.string.sp_thursday_NORMAL),
				getResources().getString(R.string.sp_friday_NORMAL),
				getResources().getString(R.string.sp_saturday_NORMAL) };

		boolean is24HourFormat = DateFormat.is24HourFormat(this);
		// ////////////////////////////////////////////////////////////////////////////
		if (is24HourFormat == true) {
			findViewById(R.id.apm_ID).setVisibility(View.INVISIBLE);
			findViewById(R.id.hour_Text01).setPadding(0, 0, 0, 0);
			if (mCalendar.get(Calendar.AM_PM) == 1) {
				hour += 12;
			}
		}

		if (is24HourFormat == false) {
			if (mCalendar.get(Calendar.AM_PM) == 0) {
				apm = (TextView) findViewById(R.id.apm_ID);
				apm.setText(R.string.sp_AM_string_NORMAL);
			} else {
				apm = (TextView) findViewById(R.id.apm_ID);
				apm.setText(R.string.sp_PM_string_NORMAL);
			}

			if (hour == 0) {
				hour = 12;
			}
		}

		int digit1 = hour / 10;
		int digit0 = hour % 10;
		/*
		 * LGSI_CHANGE_S : AlarmClock 2012-03-26, saurabh.khare@lge.com, Numbers
		 * are changed in to arabic format in alarm clock module
		 */

		int mdigit1 = minutes / 10;
		int mdigit0 = minutes % 10;
		/*
		 * LGSI_CHANGE_S : AlarmClock 2012-03-26, saurabh.khare@lge.com, Numbers
		 * are changed in to arabic format in alarm clock module
		 */
		if ("ar".equals(Locale.getDefault().getLanguage())
				|| "fa".equals(Locale.getDefault().getLanguage())) {
			/* Based on locale we are changing the values */
			mHour01 = (TextView) findViewById(R.id.hour_Text01);
			mHour01.setText(String.format(Locale.getDefault(), "%d", digit1));
			if (is24HourFormat == false && digit1 == 0) {
				mHour01.setVisibility(View.GONE);
			}
			mHour02 = (TextView) findViewById(R.id.hour_Text02);
			mHour02.setText(String.format(Locale.getDefault(), "%d", digit0));
			mMinute01 = (TextView) findViewById(R.id.min_Text01);
			mMinute01
					.setText(String.format(Locale.getDefault(), "%d", mdigit1));
			mMinute02 = (TextView) findViewById(R.id.min_Text02);
			mMinute02
					.setText(String.format(Locale.getDefault(), "%d", mdigit0));
		} else {
			mHour01 = (TextView) findViewById(R.id.hour_Text01);
			mHour01.setText(mNumDigitDrawables[digit1]);
			if (is24HourFormat == false && digit1 == 0) {
				mHour01.setVisibility(View.GONE);
			}
			mHour02 = (TextView) findViewById(R.id.hour_Text02);
			mHour02.setText(mNumDigitDrawables[digit0]);

			mMinute01 = (TextView) findViewById(R.id.min_Text01);
			mMinute01.setText(mNumDigitDrawables[mdigit1]);
			mMinute02 = (TextView) findViewById(R.id.min_Text02);
			mMinute02.setText(mNumDigitDrawables[mdigit0]);
		}
		/* LGSI_CHANGE_E : AlarmClock */

		/*
		 * LGSI_CHANGE_S 2012-02-16, sarah.ganihar@lge.com, Alarm Alert
		 * Numbers(HH:MM) to be displayed in arabic
		 */

		if (CommonUtil.isArabFarsiLanguage()) {
			mHour01.setText(CommonUtil.convertArabFarsiNum(
					Integer.toString(digit1), false));
			mHour02.setText(CommonUtil.convertArabFarsiNum(
					Integer.toString(digit0), false));
			mMinute01.setText(CommonUtil.convertArabFarsiNum(
					Integer.toString(mdigit1), false));
			mMinute02.setText(CommonUtil.convertArabFarsiNum(
					Integer.toString(mdigit0), false));
		}
		/* LGSI_CHANGE_E */

		// ////////////////////////////////////////////////////////////////////////////////////////////

		String dateStringTemp;

		dateStringTemp = yoil[mCalendar.get(Calendar.DAY_OF_WEEK)] + ", "
				+ strMONTH[mCalendar.get(Calendar.MONTH)] + " "
				+ mCalendar.get(Calendar.DATE);

		/*
		 * [START] 2012.03.14 suein1209.kim change the display time type in
		 * Japan lang
		 */
		if (CommonUtil.isAsiaLanguage(this)) {
			String dateStringkor = (mCalendar.get(Calendar.MONTH) + 1) + "/"
					+ mCalendar.get(Calendar.DATE) + " ("
					+ yoil[mCalendar.get(Calendar.DAY_OF_WEEK)] + ")";
			dateString.setText(dateStringkor);

		}
		/*
		 * LGSI_CHANGE_S : AlarmClock 2012-03-26, saurabh.khare@lge.com, Numbers
		 * are changed in to arabic format in alarm clock module
		 */
		else if (CommonUtil.isArabFarsiLanguage()) {
			/*
			 * LGSI_CHANGE_S : AlarmClock 2012-04-14, srinivas.turaga@lge.com,
			 * Added / between DD & MM to fix date separator issue in alarm
			 * clock for Arabic/Farsi
			 */
			dateString.setText(yoil[mCalendar.get(Calendar.DAY_OF_WEEK)]
					+ " "
					+ strMONTH[mCalendar.get(Calendar.MONTH)]
					+ "/"
					+ String.format(Locale.getDefault(), "%d",
							mCalendar.get(Calendar.DATE)));
			/* LGSI_CHANGE_E: AlarmClock */
		}
		/* LGSI_CHANGE_E : AlarmClock */
		else {
			dateString.setText(dateStringTemp);
		}
		/*
		 * [END] 2012.03.14 suein1209.kim change the display time type in Japan
		 * lang
		 */
	} //End Of Method update_time
	
	
	/* called by system on minute ticks */
	private final Handler mHandler = new Handler();
	
	/**
	 * suein1209.kim
	 * Show normal dialog mode
	 * @param mHour01
	 * @param mHour02
	 * @param mMinute01
	 * @param mMinute02
	 */
	private void showNormalDialog(String mHour01, String mHour02, String mMinute01, String mMinute02){
		
		setContentView(R.layout.timerdialog);
		
		LayoutInflater inflater = (LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);
        View alarmTime = inflater.inflate(R.layout.alarmdialogtime, (ViewGroup)findViewById(R.id.alarmdialog));
        ((TextView)alarmTime.findViewById(R.id.dialog_hour_Text01)).setText(mHour01);
        ((TextView)alarmTime.findViewById(R.id.dialog_hour_Text02)).setText(mHour02);
        ((TextView)alarmTime.findViewById(R.id.dialog_min_Text01)).setText(mMinute01);
        ((TextView)alarmTime.findViewById(R.id.dialog_min_Text02)).setText(mMinute02);
		
        if(is24Hours){
        	((TextView)alarmTime.findViewById(R.id.dialog_apm_ID)).setVisibility(View.INVISIBLE);
        }else{
        	((TextView)alarmTime.findViewById(R.id.dialog_apm_ID)).setVisibility(View.VISIBLE);
        }
        ((TextView)alarmTime.findViewById(R.id.dialog_apm_ID)).setText(apm);
		
		alarmDialog = new AlertDialog.Builder(this).setTitle(mTitle).setView(alarmTime)
				.setNegativeButton(R.string.sp_stop_name_NORMAL,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								dialogStopChanged();
								mPlaying = false;
								finish();
							}
						}).setPositiveButton(R.string.snooze_button,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface arg0, int arg1) {
								if(mSnooze==0){
									mSnooze = 5;
								}
								dialogSnoozeChanged();
								mPlaying = false;
								finish();
							}
						}).setOnKeyListener(new OnKeyListener() {
					public boolean onKey(DialogInterface dialog, int keyCode,
							KeyEvent event) {
						switch (keyCode) {
						case KeyEvent.KEYCODE_BACK:
							return true;
						case KeyEvent.KEYCODE_MENU:
							return true;
						case KeyEvent.KEYCODE_SEARCH:
							return true;
						case KeyEvent.KEYCODE_VOLUME_UP:
						case KeyEvent.KEYCODE_VOLUME_DOWN:
						case KEYCODE_3DCAMERA:
							Log.d(TAG, "=======Side buttons is up==========");
							// [hyunjung78.park][1458] 2011.10.18 START

							if ("1".equals(sideButtons)) {
								snoozeChanged();
							} else if ("2".equals(sideButtons)) {
								stopChanged();
							}
							return true;
						default:
							return false;
						}
					}
				}).setCancelable(false).create();
		
       	 alarmDialog.show();
	} //End of Method nomalShowDialog
	
	private void updateLayout() {
		
		Log.e(TAG, "mPouch => " + mPouch);
		
		if(alarmDialog != null){
			alarmDialog.dismiss();
		}
		mCalendar.setTimeInMillis(System.currentTimeMillis());
    	int minutes = mCalendar.get(Calendar.MINUTE);
    	int hour    = mCalendar.get(Calendar.HOUR);
    	
    	boolean is24HourFormat = DateFormat.is24HourFormat(this) ;  
    	Log.d(TAG, "===updateTime===> " +  hour + " / " + minutes) ;          		
        //////////////////////////////////////////////////////////////////////////////
        if (is24HourFormat == true) {
			Log.d(TAG, "==========24 mode==============") ;
			is24Hours = true;
			if (mCalendar.get(Calendar.AM_PM) == 1) {
				hour += 12 ;
	        } 
		}else if (is24HourFormat == false){
        	Log.d(TAG, "==========am/pm mode==============>>> " +  mCalendar.get(Calendar.AM_PM) ) ;
        	is24Hours = false;
    		if ( mCalendar.get(Calendar.AM_PM) == 0 ) {
    			apm = getText(R.string.sp_AM_string_NORMAL);;
    		}
    		else {
    			apm = getText(R.string.sp_PM_string_NORMAL);;
    		}
        	
	        if (hour == 0) {
				hour = 12;
			}
        }
                     
		int digit1 = hour / 10;
		int digit0 = hour % 10;
//		Typeface tf = Typeface.createFromAsset(getApplicationContext().getAssets(),
//        "fonts/Clockopia.ttf");
		mHour01 = (mNumDigitDrawables[digit1]);
		mHour02 = (mNumDigitDrawables[digit0]);
           
        ////////////////////////////////////////////////////////////////////////////////////////
		
		int mdigit1 = minutes / 10;
		int mdigit0 = minutes % 10;   
		
		mMinute01 = (mNumDigitDrawables[mdigit1]);
		mMinute02 = (mNumDigitDrawables[mdigit0]);
		
		/*[START] 2012.05.09 suein1209.kim INTERNAL_TEST.LAB1_11 - Defect #158673, Medic : 7056*/
		if(mPouch){
			showPouchDialog();
			
		}else{
			showNormalDialog(mHour01, mHour02, mMinute01, mMinute02);
			
		} //End Of if
		/*[END] 2012.05.09 suein1209.kim INTERNAL_TEST.LAB1_11 - Defect #158673, Medic : 7056*/
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		Log.i(TAG, "onDestory");
		finishReady();
	}



	private void finishReady() {
		Log.d(TAG, "================setNextAlert================");
        Alarms.setNextAlert(this);
//        multiCheck(this, mId, mTime);
		//[hyunjung78.park] 2011.08.16 when alarm alert from lock screen, send broadcast to lock screen when press stop button START
		Intent alarm_intent = new Intent();
	 	alarm_intent.setAction( "alarm.current.nextAlarm" );
	 	sendBroadcast(alarm_intent);
        //[hyunjung78.park]2011.08.16 when alarm alert from lock screen, send broadcast to lock screen when press stop button END
	 	Log.d(TAG, "============[[ finishReady() ]]========= mSavings()" +  mSavings.size()); 
	 	
	 	Intent kk	=	null ;       
        for (int i=0; i < mSavings.size(); i++) {
        	kk = (Intent)(mSavings.elementAt(i));
        	Log.d(TAG, "remove=ID==> " +  kk.getIntExtra("id", -1) + "  mSavings()=" + mSavings.size() ); 
        	mSavings.removeElementAt(i);
      		break;
        }     
                                   
		if (kk != null) {
			Log.d(TAG, "Intent kk==========" + kk.toString());
			this.startActivity(kk);    
		}    
	 	
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		Log.i(TAG, "onPause");
		//[mo2sangbong.lee][1817] 2011.11.11 START
		if (mPouchIntentReceiver != null) {
			try{
				unregisterReceiver(mPouchIntentReceiver);
			}catch(Exception e){
				e.printStackTrace();
			}
		}
		//[mo2sangbong.lee][1817] 2011.11.11 END		
	}



	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Log.i(TAG, "onResume");
		/*[START] 2012.05.16 suein1209.kim VZW auto snooze alarm issue, when bluetooth calling*/
//		AlarmAlertWakeLock.acquireScreenWakeLock(this);
		/*[END] 2012.05.16 suein1209.kim VZW auto snooze alarm issue, when bluetooth calling*/
		
		IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_DOCK_EVENT);
        registerReceiver(mPouchIntentReceiver, filter, null, mHandler);
        
	}
	
	private final BroadcastReceiver mPouchIntentReceiver = new BroadcastReceiver() {
    	@Override
        public void onReceive(Context context, Intent intent) {
    		Log.e(TAG, "intent.getAction() => " + intent.getAction());
    		mPouch = PouchMode.getDockState(intent);
    		updateLayout();
        }    
    };

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		Log.i(TAG, "onStop");
		/*[START] 2012.05.16 suein1209.kim VZW auto snooze alarm issue, when bluetooth calling*/
//		if(mPlaying == true){
//			if (mSnooze > 0) 
//			{
//				dialogSnoozeChanged();
//	         	finish();                     
//	         	return ;
//			}
//			else if (mSnooze == 0) 
//			{
//	         	ContentValues values = new ContentValues();
//	         	mSnooze = 5;
//	         	values.put("snooze", 5);
//	         	mResolver.update(ALProvider.CONTENT_ALARMS_URI, values, "_id=" + mId, null);	         	
//	         	dialogSnoozeChanged();
//	         	finish();
//	         	return ; 	
//	        }
//		}
//		releaseLocks();
		/*[END] 2012.05.16 suein1209.kim VZW auto snooze alarm issue, when bluetooth calling*/
	}
	
	/*[START] 2012.05.16 suein1209.kim VZW auto snooze alarm issue, when bluetooth calling*/
//	private void releaseLocks() {
//    	synchronized ( this ) {
//    		AlarmAlertWakeLock.release();
//		}
//    }
	/*[END] 2012.05.16 suein1209.kim VZW auto snooze alarm issue, when bluetooth calling*/


	@Override
	public void finish() {
		super.finish();
		Log.i(TAG, "finish");
	}

	private static final int KEYCODE_3DCAMERA = 92;
    /**
     *  volume up/down => snooze or stop
     * @param keyCode int
     * @param event KeyEvent
     * @return boolean
     * @see android.view.KeyEvent$Callback#onKeyUp(int, KeyEvent)
     */
	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		switch (keyCode) {
		/* [START] 2012.03.26 suein1209.kim refectory side button */
		case KeyEvent.KEYCODE_VOLUME_UP:
		case KeyEvent.KEYCODE_VOLUME_DOWN:
		case KEYCODE_3DCAMERA:
			Log.d(TAG, "=======Side buttons is up==========");
			// [hyunjung78.park][1458] 2011.10.18 START

			if ("1".equals(sideButtons)) {
				snoozeChanged();
			} else if ("2".equals(sideButtons)) {
				stopChanged();
			}
			return true;

			// [hyunjung78.park][1458] 2011.10.18 END
		case KeyEvent.KEYCODE_BACK | KeyEvent.KEYCODE_MENU
				| KeyEvent.KEYCODE_SEARCH:
			break;

		default:
			break;
		}

		return false;
	}    
    
    /**
     * Method onKeyDown.
     * @param keyCode int
     * @param event KeyEvent
     * @return boolean
     * @see android.view.KeyEvent$Callback#onKeyDown(int, KeyEvent)
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) { 
    	switch (keyCode) { 		
			case KeyEvent.KEYCODE_VOLUME_UP :
				Log.d(TAG, "======KEYCODE_VOLUME_UP is down==========");
				return true; 
			      
			case KeyEvent.KEYCODE_VOLUME_DOWN: 
				Log.d(TAG, "======KEYCODE_VOLUME_DOWN is down==========");
				return true;
			
			default :
				break;
    	}
    	
		return false; 	
	} 
    ////////////////////////////////////////////////////////// 	


	private void dialogStopChanged() {
		// TODO Auto-generated method stub
		mResolver.delete(ALProvider.CONTENT_CALCU_URI, "aid = " + mId + " and aindex > 0", null);

    	Alarms.noRepeatChecking(this, mId, false);
           
        NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    	nm.cancel(mId);
	}
	
	private void dialogSnoozeChanged() {
		
		/*default snooze 5m*/
		if(mSnooze <= 0){
			mSnooze = 5;
		} //End Of if
		
		Log.i(TAG, "dialogSnoozeChanged mId : "+mId+", mMemo : "+mMemo+", mSnooze : "+mSnooze+", mTone : "+mTone+", mVib : "+mVib+", mstrPuzzle : "+mstrPuzzle+", mTime : "+mTime);
		
		snoozeSetting(this, i, mResolver, mId, mMemo, mSnooze, mTone, mVib, mstrPuzzle, mTime);
		
	}
	
	private static boolean get24HourMode(final Context context) {
        return android.text.format.DateFormat.is24HourFormat(context);
    }
	private boolean getDateFormat(Context context) {
    	if (get24HourMode(context) == true) {
    		m1Format = M24_CHECK;
    		return true;
    	}    	
    	m1Format = M12_CHECK;
    	return false;
    }
	
	private String m1Format;
    /**
     * Field M24_CHECK.
     * (value is ""kk:mm"")
     */
    static final String M24_CHECK = "kk:mm";   
	/**
	 * Field M12_CHECK.
	 * (value is ""h:mm"")
	 */
	static final String M12_CHECK = "h:mm";
	
	private String getCalendarNow(long time , Context context, int snooze) {
		time = time + (1000 * 60 * snooze);
    	Calendar aa = Calendar.getInstance( );
    	aa.setTimeInMillis( time );

    	// is24HourFormat
    	if ( getDateFormat(context) ) {
    		CharSequence alarmtime = DateFormat.format(m1Format, aa);
	    	return (alarmtime.toString() + ". " + context.getText(R.string.sp_alarm_right_ment_NORMAL).toString());
    	}
	    // is12HourFormat
    	else {
    		CharSequence alarmtime = DateFormat.format(m1Format, aa);
	        boolean bAPM = aa.get(Calendar.AM_PM) == 0;
	        if ( bAPM ) {
	        	return (alarmtime.toString() + " " + context.getText(R.string.sp_AM_string_NORMAL).toString()
	        			+ "." + " " + context.getText(R.string.sp_alarm_right_ment_NORMAL).toString());
	        } else {
	        	return (alarmtime.toString() + " " + context.getText(R.string.sp_PM_string_NORMAL).toString()
	        			+ "." + " " + context.getText(R.string.sp_alarm_right_ment_NORMAL).toString());
	        }
    	}
    }
	
	private void snoozeSetting(Context context, Intent intent, ContentResolver resolver, int id, String  memo
    		, int snooze, String tone, String vib, String puzzle, long rTime) {
    	
    	int  pk   	   =	intent.getIntExtra("pk", 0);
    	resolver.delete(ALProvider.CONTENT_CALCU_URI, "_id = " + pk,  null);
    	autoSnoozeGoAhead(context, id, memo, snooze, tone, vib, puzzle);
 
        CharSequence from =  context.getText(R.string.sp_snooze_ment_NORMAL).toString() + "(" + memo + ")";
        if (memo == null || "".equals(memo.trim())) {
           	from =  context.getText(R.string.sp_snooze_ment_NORMAL).toString();  
        }

        CharSequence[] snooze_button_popup = context.getResources().getTextArray(R.array.sp_snooze_popup_NORMAL);
        int[] timeMap = {5,10,15,20,25,30,60};
        String showMessage = "";
        for (int i = 0; i < timeMap.length; i++) {
        	if (timeMap[i] == snooze) {
        		showMessage = (String)snooze_button_popup[i];
        		break;
        	}
        }
        CharSequence message = context.getText(R.string.alarm_ment1).toString() + " " +  getCalendarNow(rTime, context, snooze);
            
        NotificationManager notiManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        notiManager.cancel(id);
        Toast.makeText(context, showMessage, Toast.LENGTH_SHORT).show();
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////
        
        Intent cancelSnooze = new Intent(this, ALReceiver.class);
        cancelSnooze.setAction(Alarms.CANCEL_SNOOZE);
        cancelSnooze.putExtra( "id", mId );
        PendingIntent broadcast = PendingIntent.getBroadcast(this, mId, cancelSnooze, 0);
        
        Notification notif = new Notification(R.drawable.stat_notify_alarm, from, 0 );
        // Set the info for the views that show in the notification panel.
            
        notif.flags |= Notification.FLAG_AUTO_CANCEL;
        
        if((CommonUtil.getBuildOperator() == OPERATOR.DCM 
        		|| CommonUtil.getBuildOperator() == OPERATOR.VZW)
        		&& CommonUtil.isPowerLEDSetInSettings(mResolver) == 0){
        	
        	notif.flags |= Notification.DEFAULT_LIGHTS;
        	
        }else{
        	
        	notif.flags |= Notification.FLAG_SHOW_LIGHTS;	
        	notif.defaults |= Notification.DEFAULT_LIGHTS;
        	
        } //End Of ifif
//        notif.ledARGB = 0xFF00FF00;
//        notif.ledOnMS = 500;
//        notif.ledOffMS = 500;

        notif.setLatestEventInfo(context, from, message, broadcast);
        notif.deleteIntent = broadcast;
        notiManager.notify(id,  notif);
        ///////////// end /////////////////////////////////////
    }
	
	private void autoSnoozeGoAhead(Context context, int mID, String mMEMO, int mSNOOZE, String mTONE, String mVIB, String mPuzzle){
		
		Log.i(TAG, "autoSnoozeGoAhead");
		
    	NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
	    nm.cancel(mID);
    	
        
    	int snooze_count = 0;
		Cursor cur = null;
		try {
			cur = mResolver.query(ALProvider.CONTENT_CALCU_URI, new String[] { "_id" }, "aid=" + mID + "  and  aindex > 0" , null, null);
			//[mo2sangbong.lee][WBT#267998] 2011.10.25 START
			if ( cur != null ) {
				snooze_count = cur.getCount();
			}
			//[mo2sangbong.lee][WBT#267998] 2011.10.25 END
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (cur != null)
				cur.close();
		}
		
		int totalCount = 0;
		if ( snooze_count > 0 ) {
			mResolver.delete(ALProvider.CONTENT_CALCU_URI, "aid=" + mID + "  and  aindex > 0",  null);
			totalCount = (snooze_count + 1);
		} else if (snooze_count == 0) { // last snooze check 
			totalCount = 5;
		}
		
		final String[] alarmNeedColumns = { "daysofweek", "hour", "minutes" };
		int daysofweek = 0, hour = 0, minutes = 0;
        Cursor cc = null;
		try {
			cc = mResolver.query(ALProvider.CONTENT_ALARMS_URI, alarmNeedColumns, "_id=" + mID, null, null );
			//[mo2sangbong.lee][WBT#267999] 2011.10.25 START
	        if ( cc != null && cc.moveToFirst() ) {
			//[mo2sangbong.lee][WBT#267999] 2011.10.25 END
        		daysofweek	=  cc.getInt(0);
        		hour		=  cc.getInt(1);
        		minutes		=  cc.getInt(2);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (cc != null)
				cc.close();
		}
        
        Calendar c3 = Calendar.getInstance();
        c3.set(Calendar.SECOND, 0);
        c3.set(Calendar.MILLISECOND, 0);
        long snooze_time = c3.getTimeInMillis();
        
        ContentValues values = null;    	         
        Date dd1 = null;
         
        //long nextTime = 0;
        Log.d(TAG, " == SnoozeRefreshing === START mTIME =======> " + snooze_time + "  /  snooze(min) interval => " + mSNOOZE );   
        for (int i = 1 ;  i <= totalCount; i++ )                            
        {                
        	long aa	= snooze_time + (1000 * 60 * i * mSNOOZE);
        	c3.setTimeInMillis( aa );
        	//if (i == 1) {
        	//	nextTime = aa;
        	//}
        	
        	dd1 = c3.getTime();   
            Log.d(TAG,  i + " th=>" + c3.getTimeInMillis() + " Time=>" + dd1.toString() );     
            Log.d(TAG,  "============================================================"  );
                                                     
            values = new ContentValues();
            values.put( "aid",   	mID);  
            values.put( "aindex",  	i ); 
            ////////////////////////////////////////////////
            values.put( "hour",  hour );        
            values.put( "minutes",  	minutes );
            values.put( "daysofweek",  	daysofweek ); 
            values.put( "enabled",  	1 );
            values.put( "time",  		c3.getTimeInMillis() );
            values.put( "status",  		"S" );
            if (i != totalCount) {
            	values.put( "stop", "" );
            }else {
            	values.put( "stop", "stop" );
            }  
            ////////////////////////////////////////////////                      
            mResolver.insert(ALProvider.CONTENT_CALCU_URI, values);       		
        }
	}
	
	
	/**
     * snooze (Off / 5m / 10m/ 20m / 30m/ 60m)
     * @param id
     * @return
     */
    private int getSnoozeTime(Context context, int alarmId) {
    	int snoozeSet = 0 ;   
        
        mResolver = context.getContentResolver(); 
        Cursor cc = null;
        try {
//        	cc = mResolver.query(  ALProvider.CONTENT_ALARMS_URI, mIsUseVolumeControl ? ALARM_NEED_COLUMNS_2 : ALARM_NEED_COLUMNS, "_id=" + alarmId, null, null );
        	cc = mResolver.query(  ALProvider.CONTENT_ALARMS_URI, ALARM_NEED_COLUMNS, "_id=" + alarmId, null, null );
        	//[mo2sangbong.lee][WBT#268001] 2011.10.25 START
            if ( cc != null && cc.moveToFirst() ) {
            //[mo2sangbong.lee][WBT#268001] 2011.10.25 END
            	do {  
            		snoozeSet =	cc.getInt(ALARM_NEED_COLUMNS_IDX_ALARM_SNOOZE);
    				if (!"Off".equalsIgnoreCase(cc.getString(ALARM_NEED_COLUMNS_IDX_ALARM_TONE))) {
    					temp_TONE =	cc.getString(ALARM_NEED_COLUMNS_IDX_ALARM_TONE);
    				} else {
    					temp_TONE =	"Off";
    				}
    				temp_VIB = cc.getString(ALARM_NEED_COLUMNS_IDX_ALARM_VIB);
    				temp_MEMO = cc.getString(ALARM_NEED_COLUMNS_IDX_ALARM_MEMO); 
    				temp_PUZZLE = cc.getString(ALARM_NEED_COLUMNS_IDX_ALARM_PUZZLE);
            	} while(cc.moveToNext());
            }
        } catch ( Exception e ) {
        	e.printStackTrace();
        } finally {
        	if ( cc != null )
        		cc.close();
        }
        
    	return snoozeSet;
    }
    
    
    /**
     *   (multialarm, multisnooze checked = true) => save 
     */
    private static final String[] CALCU_COLS = { "_id",  "aid",  "time", "aindex", "status", "stop" };
    private boolean multiCheck(int mId, long mTime, boolean newIntentYN) {
    	boolean returnTag = false;
    	NotificationManager nm = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    	
    	Cursor cc = null;
    	try {
    		if (newIntentYN == true) {
        		cc = mResolver.query(Uri.parse(("content://com.lge.clock.alarmclock.ALProvider/calcus").concat("?calcuqueryType=1")), CALCU_COLS, 
    					 							"enabled = '1' and time = " + mTime + " and aid >= " + mId, null, "time, status, aid" );
        	} else {
        		cc = mResolver.query(Uri.parse(("content://com.lge.clock.alarmclock.ALProvider/calcus").concat("?calcuqueryType=1")), CALCU_COLS, 
    												 "enabled = '1' and time = " + mTime + " and aid != " + mId, null, "time, status, aid" );
        	}
        	
        	if (cc != null && cc.getCount() > 0) {//[hyunjung78.park] 2011.08.09 cursor null check
        		returnTag = true;
        	}
        	
        	Log.d(TAG, "====multiCheck==== / Id : " + mId + " time : " + mTime + " <==> " + returnTag);
        	if ( cc != null && cc.moveToFirst() ) {
        		do {
        			int snooze = 0;
    				int pk     = cc.getInt(0);
    				int aid    = cc.getInt(1);
    			    int aindex = cc.getInt(3);
    			    	         
    			    Intent intent = new Intent(this, AlarmDialog.class);
    			    intent.putExtra("id", aid);
    			    intent.putExtra("time", mTime);
    			    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
    			    intent.putExtra("multi", "yes");
    			        
    			    Log.d(TAG, " multiCheck - alarm Next ID - " + aid + "  ========================> " + aindex);
    			         
    			    if (aindex == 0) {
    			    	Log.d(TAG, "  ============= ALARM =============  " );
    			        intent.putExtra( "gubun", "alarm" );
    			        snooze = getSnoozeTime(this, aid);
    			        intent.putExtra( "snooze", snooze );
    			        if ( snooze > 0 ) {
    				       	intent.putExtra( "stop", "" );
    				    } else {
    				       	intent.putExtra( "stop", "stop" );
    				    }
    			    } else {
    			    	Log.d(TAG, "  ============= SNOOZE =============  " );
    			        String stop = cc.getString(5);
    			        intent.putExtra( "pk", pk );
    			        intent.putExtra( "gubun", "snooze" );
    			        snooze = getSnoozeTime( this, aid );
    			        intent.putExtra( "snooze",  snooze );
    			        if ( stop != null && stop.equalsIgnoreCase("stop") ) {
    				       	intent.putExtra( "stop", "stop" );
    				    } else {
    				       	intent.putExtra( "stop", "");
    				    }
    				    
    				    mResolver.delete(ALProvider.CONTENT_CALCU_URI, "_id = " + pk,  null);
    			    }
    			    
    			    intent.putExtra("memo",   temp_MEMO);
				    intent.putExtra("puzzle", temp_PUZZLE);
				    intent.putExtra("tone",   temp_TONE);
				    intent.putExtra("vib",    temp_VIB);
    			    
    			    // The details of our fake message
				    CharSequence from = getText(R.string.alarm);
				    /*CharSequence from = null;
				    if (temp_MEMO == null || "".equals(temp_MEMO.trim())) {
				       	from = getText(R.string.alarm).toString();
				    } else {
				       	from = getText(R.string.alarm).toString();
				       	//+ "(" + temp_MEMO + ")";
				    }*/
				                        
				    CharSequence message = getText(R.string.user_select);
				    //[mo2sangbong.lee][1596] 2011.10.26 START
				    PendingIntent contentIntent = PendingIntent.getActivity(this, aid, intent, 0);
				    //[mo2sangbong.lee][1596] 2011.10.26 END
				    Notification notif = new Notification(R.drawable.stat_notify_alarm, from, mTime);
				    // Set the info for the views that show in the notification panel.
				    notif.setLatestEventInfo(this, from, message, contentIntent);
				    
			        if((CommonUtil.getBuildOperator() == OPERATOR.DCM 
			        		|| CommonUtil.getBuildOperator() == OPERATOR.VZW)
			        		&& CommonUtil.isPowerLEDSetInSettings(mResolver) == 0){
			        	
			        	notif.flags |= Notification.DEFAULT_LIGHTS;
			        	
			        }else{
			        	
			        	notif.flags |= Notification.FLAG_SHOW_LIGHTS;	
			        	notif.defaults |= Notification.DEFAULT_LIGHTS;
			        	
			        } //End Of if
//				    notif.ledARGB  = LED_RGB;
//				    notif.ledOnMS  = LED_ON_MS;
//				    notif.ledOffMS = LED_OFF_MS;
				    nm.notify(aid, notif);
				    
    			    boolean check = false;
    			    int nSavingsSize = mSavings.size();
    		        for ( int k = 0; k < nSavingsSize; k++ ) {
    		           	Intent aa = (Intent)mSavings.elementAt(k);
    		           	if ( aid == aa.getIntExtra("id", 0) ) {
    		           		check = true;
    		           		break;
    		           	}
    		        }

    		        Log.d(TAG, "======mSavings.size() ==>" + mSavings.size());
    		        if (check == false) {
    		           	Log.d(TAG, mSavings.size() + "=======multi add OK id====>" + aid);
    		           	mSavings.add(intent);
    		        }
        		} while( cc.moveToNext() );
        	}
    	} catch ( Exception e ) {
    		e.printStackTrace();
    	} finally {
    		if ( cc != null )
    			cc.close();
    	}
        
        return returnTag;
    }

}
